<?php

namespace app\admin\controller\wanlshop;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Session;
use app\admin\controller\Ajax;
use think\Exception;

/**
 * 商品管理
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{

    /**
     * Goods模型对象
     * @var \app\admin\model\wanlshop\Goods
     */
    protected $model = null;
    protected $shop_model = null;
    protected $goods_shop_model = null;
    protected $goods_spu_model = null;
    protected $goods_sku_model = null;
    protected $unitList = null;
    protected $searchFields = 'id,title';
    
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wanlshop\Goods;
        $this->shop_model = new \app\admin\model\wanlshop\Shop;
        $this->goods_shop_model = new \app\admin\model\wanlshop\GoodsShop;
        $this->goods_spu_model = new \app\index\model\wanlshop\GoodsSpu;
        $this->goods_sku_model = new \app\index\model\wanlshop\GoodsSku;

        $tree = Tree::instance();
        // 1.0.2升级 过滤隐藏
        $this->unitList = $this->model->getUnitList();
        $tree->init(model('app\index\model\wanlshop\Category')->where(['type' => 'goods', 'isnav' => 1])->field('id,pid,name')->order('weigh asc,id asc')->select());
        $this->assignconfig('channelList', $tree->getTreeArray(0));
        $this->view->assign("flagList", $this->model->getFlagList());
        $this->view->assign("channelList", $this->model->getChannelList());
        $this->view->assign("stockList", $this->model->getStockList());
        $this->view->assign("specsList", $this->model->getSpecsList());
        $this->view->assign("distributionList", $this->model->getDistributionList());
        $this->view->assign("activityList", $this->model->getActivityList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("groundingList", $this->model->getGroundingList());
        $this->view->assign("unitList", $this->unitList);
        $this->view->assign("platformList", $this->model->getPlatformList());
        $this->view->assign("categoryList", (new Ajax)->getgoodscategorylist(104,'array'));
        
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前管理员店铺id 
        $_admin = Session::get('adminshop');

        //当前店铺id
        $shop_id = Session::get('shop');

        //是否显示tab
        $show_tab = 0;

        //是否显示copy
        $show_copy = 0;

        if($_admin == $shop_id && $shop_id != 1){
            $show_tab = 1;
        }

        if($_admin == $shop_id && $shop_id == 1){
            $show_copy = 1;
        }

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $conditions = [];
            $conditions['gdtype'] = '0';
            $conditions['goods.status'] = 'normal';
            $total = $this->model
                ->with(['category', 'shopsort', 'shop'])
                ->where($where)
                ->where($conditions)
                ->where('fa_wanlshop_goods.shop_id', '=', $shop_id)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['category', 'shopsort', 'shop'])
                ->where($where)
                ->where($conditions)
                ->where('fa_wanlshop_goods.shop_id', '=', $shop_id)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
// print_r($this->model->getLastSql());die;
            foreach ($list as $row) {
                $row->getRelation('category')->visible(['name']);
                $row->getRelation('shopsort')->visible(['name']);
                $row->getRelation('shop')->visible(['shopname']);
            }

            $list = collection($list)->toArray();

            foreach ($list as $key => &$value) {
                $value['show_copy'] = $show_copy;
                $conditions = [];
                $conditions['status'] = 'normal';
                $conditions['goods_id'] = $value['id'];
                $conditions['state'] = '0';
                $value['stocks'] = $this->goods_sku_model->where($conditions)->sum('stock');
                $ids = $this->goods_shop_model->where(['goods_id'=>$value['id']])->column('new_goods_id');
                $num_on_sale = 0;
                if (count($ids)>0) {
                    $shop_ids = $this->model->where(['id'=>['in',$ids],'grounding'=>'1'])->column('shop_id');
                    $conditions = [];
                    $conditions['id'] = ['in',$shop_ids];
                    $conditions['status'] = 'normal';

                    // 获取总数
                    $num_on_sale = $this->shop_model->where($conditions)->count();
                }
                $value['on_sale_shop'] = $num_on_sale;
                //推广码
                $value['promotion_qr_data'] = urlencode(json_encode(['page' => 'pages/product/goods', 'scene' => ['id' => $value['id']]]));
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->view->assign('show_tab',$show_tab);
        $this->view->assign('show_copy',$show_copy);
        return $this->view->fetch();
    }

    /**
     * 选择链接
     */
    public function select()
    {
        if ($this->request->isAjax()) {
            return $this->index();
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        //设置过滤方法
        $this->request->filter(['']);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                // 判断产品属性是否存在
                // empty($params['spuItem']) ? $this->error(__('请完善：销售信息 - 产品属性')) : '';
                $result = false;
                Db::startTrans();
                try {

                    // $spudata = isset($params['spu']) ? $params['spu'] : $this->error(__('请填写销售信息-产品属性'));
                    // $spuItem = isset($params['spuItem']) ? $params['spuItem'] : $this->error(__('请填写销售信息-产品属性-产品规格'));

                    $skudata = isset($params['sku']) && !empty($params['sku'])?$params['sku'] : [];

                    $spudata = isset($params['spu']) && !empty($params['spu'])?$params['spu'] : '';
                    $spuItem = isset($params['spuItem']) && !empty($params['spuItem'])?$params['spuItem'] : [];

                    // 获取自增ID
                    //  $this->model->shop_id = $this->shop->id;
                    $this->model->shop_id =  Session::get('shop');
                    //  $this->model->brand_id = $params['brand_id'];
                    $this->model->category_id = $params['category_id'];
                    if (isset($params['attribute'])) {
                        $this->model->category_attribute = json_encode($params['attribute'], JSON_UNESCAPED_UNICODE);
                    }

                    if ($this->model->shop_id != 1) {
                        $this->model->selfsupport = '1';
                    }
                    $this->model->gdtype = 0;
                    $this->model->title = $params['title'];
                    $this->model->image = $params['image'];
                    $this->model->images = $params['images'];
                    // $this->model->description = $params['description'];
                    $this->model->stock = $params['stock'];
                    $this->model->code = $params['code'];
                    $this->model->unit = $params['unit'];
                    // $this->model->tags = $params['tags'];
                    $this->model->flag = $params['flag'];
                    $this->model->grounding = $params['grounding'];
                    $this->model->channel = $params['channel'];
//                  $this->model->status = $params['status'];
                    $this->model->content = $params['content'];
                    $this->model->video = $params['video'];
//                  $this->model->shop_category_id = $params['shop_category_id'];
                    $this->model->price = $params['price'];
                    $this->model->freight_id = $params['freight_id'];
                    $this->model->publishing_platform = $params['publishing_platform'];
                    if ($this->model->save()) {
                        $result = true;
                    }
                    // 写入SPU
                    $spu = [];
                    if (!empty($spudata)) {
                        foreach (explode(",", $spudata) as $key => $value) {
                            $spu[] = [
                                'goods_id' => $this->model->id,
                                'name'     => $value,
                                'item'     => $spuItem[$key]
                            ];
                        }
                    }else{
                        $spu[] = [
                            'goods_id' => $this->model->id,
                            'name'     => $this->unitList[$this->model->unit],
                            'item'     => $this->unitList[$this->model->unit],
                        ];
                    }

                    if (!$this->goods_spu_model->allowField(true)->saveAll($spu)) {
                        $result == false;
                    }

                    
                    // 写入SKU
                    $sku = [];
                    $goods_min_price = $params['price'];
                    if (count($skudata) > 0) {
                        foreach ($params['sku']['sku_name'] as $_key => $_value) {
                            $sku[] = [
                                'goods_id'      => $this->model->id,
                                'difference'    => $_value,
                                'code'          => $params['sku']['skucode'][$_key],
                                'cost_price'    => $params['sku']['cost_price'][$_key], // 1.0.8升级
                                'channel_price' => $params['sku']['channel_price'][$_key], // 1.0.8升级
                                'price'         => $params['sku']['price'][$_key],
                                'stock'         => $params['sku']['stocks'][$_key],
                                'warn_stock'   => $params['sku']['warn_stock'][$_key],
                                'sn'            => $params['sku']['skucode'][$_key]
                            ];
                        }
                        $goods_min_price = min($params['sku']['price']);
                    }else{
                        $sku[] = [
                            'goods_id'      => $this->model->id,
                            'difference'    => $this->unitList[$this->model->unit],
                            'code'          => $params['code'],
                            'cost_price'    => $params['price'], // 1.0.8升级
                            'channel_price' => $params['price'], // 1.0.8升级
                            'price'         => $params['price'],
                            'stock'         => 99,
                            'warn_stock'   => 1,
                            'sn'            => $params['code']
                        ];
                    }
                    if (!$this->goods_sku_model->allowField(true)->saveAll($sku)) {
                        $result == false;
                    }

                    if ($goods_min_price != $params['price'] ) {
                         if (!$this->model->where('id',$this->model->id)->update(['price'=>$goods_min_price])) {
                            $result == false;
                        }
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $shop_id = Session::get('shop');//$this->shop->id;
        // 判断是否存在品牌
        $row['brand'] = model('app\index\model\wanlshop\Brand')->where(['state' => 1])->count();
        // 判断是否有店铺分类
        $row['shopsort'] = model('app\index\model\wanlshop\ShopSort')->where('shop_id', $shop_id)->count();
        // 判断是否有运费模板
        $row['freight'] = model('app\index\model\wanlshop\ShopFreight')->where('shop_id', $shop_id)->count();
        // 判断是否有寄件人信息
        $row['config'] = model('app\index\model\wanlshop\ShopConfig')->where('shop_id', $shop_id)->find();
        // 打开方式
        $this->assignconfig("isdialog", IS_DIALOG);
        $this->view->assign("row", $row);

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        //设置过滤方法
        $this->request->filter(['']);
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        // 查询SKU
        $skuItem = model('app\index\model\wanlshop\GoodsSku')
            ->where(['goods_id' => $ids, 'state' => 0])
            ->field('id,thumbnail,difference,price,market_price,stock,weigh,sn,sales,state,cost_price,channel_price,code as skucode,warn_stock')
            ->select();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                // 判断产品属性是否存在
                // empty($params['spuItem']) ? $this->error(__('请完善：销售信息 - 产品属性')) : '';
                $result = false;
                Db::startTrans();
                try {
                    // $spudata = isset($params['spu']) ? $params['spu'] : $this->error(__('请填写销售信息-产品属性'));
                    // $spuItem = isset($params['spuItem']) ? $params['spuItem'] : $this->error(__('请填写销售信息-产品属性-产品规格'));

                    $skudata = isset($params['sku']) && !empty($params['sku'])?$params['sku'] : [];

                    $spudata = isset($params['spu']) && !empty($params['spu'])?$params['spu'] : '';
                    $spuItem = isset($params['spuItem']) && !empty($params['spuItem'])?$params['spuItem'] : [];


                    // 写入表单
                    $data = $params;
                    if (isset($data['attribute'])) {
                        $data['category_attribute'] = json_encode($data['attribute'], JSON_UNESCAPED_UNICODE);
                    }

                    $result = $row->allowField(true)->save($data);
                    // 删除原来数据,重新写入SPU
                    model('app\index\model\wanlshop\GoodsSpu')
                        ->where('goods_id', 'in', $ids)
                        ->delete();



                    // 写入SPU
                    $spu = [];
                    if (!empty($spudata)) {
                        foreach (explode(",", $spudata) as $key => $value) {
                            $spu[] = [
                                'goods_id' => $ids,
                                'name'     => $value,
                                'item'     => $spuItem[$key]
                            ];
                        }
                    }else{
                        $spu[] = [
                            'goods_id' => $ids,
                            'name'     => $this->unitList[$data['unit']],
                            'item'     => $this->unitList[$data['unit']],
                        ];
                    }

                    if (!$this->goods_spu_model->allowField(true)->saveAll($spu)) {
                        $result == false;
                    }

                    //标记旧版SKU数据
                    $oldsku = [];
                    foreach ($skuItem as $value) {
                        $oldsku[] = [
                            'id'    => $value['id'],
                            'state' => 1
                        ];
                    }
                    if (!$this->goods_sku_model->allowField(true)->saveAll($oldsku)) {
                        $result == false;
                    }

                    // 写入SKU
                    $sku = [];
                    $goods_min_price = $params['price'];
                    if (count($skudata) > 0) {
                        foreach ($params['sku']['sku_name'] as $_key => $_value) {
                            $sku[] = [
                                'goods_id'      => $ids,
                                'difference'    => $_value,
                                'code'          => $params['sku']['skucode'][$_key],
                                'cost_price'    => $params['sku']['cost_price'][$_key], // 1.0.8升级
                                'channel_price' => $params['sku']['channel_price'][$_key], // 1.0.8升级
                                'price'         => $params['sku']['price'][$_key],
                                'stock'         => $params['sku']['stocks'][$_key],
                                'warn_stock'   => $params['sku']['warn_stock'][$_key],
                                'sn'            => $params['sku']['skucode'][$_key]
                            ];
                        }
                        $goods_min_price = min($params['sku']['price']);
                    }else{
                        $sku[] = [
                            'goods_id'      => $ids,
                            'difference'    => $this->unitList[$data['unit']],
                            'code'          => $params['code'],
                            'cost_price'    => $params['price'], // 1.0.8升级
                            'channel_price' => $params['price'], // 1.0.8升级
                            'price'         => $params['price'],
                            'stock'         => 99,
                            'warn_stock'   => 1,
                            'sn'            => $params['code']
                        ];
                    }
                    if (!$this->goods_sku_model->allowField(true)->saveAll($sku)) {
                        $result == false;
                    }

                    if ($goods_min_price != $params['price'] ) {
                         if (!$this->model->where('id',$row['id'])->update(['price'=>$goods_min_price])) {
                            $result == false;
                        }
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $spuData = model('app\index\model\wanlshop\GoodsSpu')->all(['goods_id' => $ids]);
        $suk = [];
        foreach ($skuItem as $vo) {
            $suk[] = explode(",", $vo['difference']);
        }
        $spu = [];
        foreach ($spuData as $vo) {
            $spu[] = $vo['name'];
        }
        $spuItem = [];
        foreach ($spuData as $vo) {
            $spuItem[] = explode(",", $vo['item']);
        }
        $skulist = [];
        foreach ($skuItem as $vo) {
            $skulist[$vo['difference']] = $vo;
        }
        $row->grounding = (string)  $row->grounding;
        $this->assignconfig('spu', $spu);
        $this->assignconfig('spuItem', $spuItem);
        $this->assignconfig('sku', $suk);
        $this->assignconfig('skuItem', $skulist);
        $this->assignconfig('categoryId', $row['category_id']);
        $this->assignconfig('attribute', json_decode($row['category_attribute']));

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 添加类目属性
     */
    public function attribute()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->request("id");
            // 1.0.8升级  获取父级类目属性
            $tree = Tree::instance();
            $tree->init(collection(model('app\index\model\wanlshop\Category')->select())->toArray(), 'pid');
            $list = model('app\index\model\wanlshop\Attribute')
                ->where('category_id', 'in', $tree->getParentsIds($id, true))
                ->where('status', 'normal')
                ->select();
            $this->success('查询成功', '', $list);
        }
        $this->error(__('Parameter %s can not be empty', ''));
    }

    public function resubmit($ids = null)
    {
        $id_arr = explode(',', $ids);
        $all_ids = [];
        foreach ($id_arr as $key => $value) {
            $row = $this->model->get($value);
            if ($row) {
                $all_ids[] = $value;
            }
        }
        // $row = $this->model->get($ids);
        // if (!$row) {
        //     $this->error(__('No Results were found'));
        // }
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $ids = $this->request->get('ids');
            if (empty($ids)) {
                return json([]);
            }

            //查询已复制过当前商品的店铺
            // $shop_ids = $this->goods_shop_model->where('goods_id',$ids)->column('shop_id');
            $shop_ids[] = 1;
            // $shop_ids = array_unique($shop_ids);
            $conditions = [];
            $conditions['id'] = ['not in',$shop_ids];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->shop_model
                ->where($where)
                ->where($conditions)
                ->order($sort, $order)
                ->count();

            $list = $this->shop_model
                ->where($where)
                ->where($conditions)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $ids = implode('-', $all_ids);
        $this->assignConfig("goods_id", $ids);
        return $this->view->fetch();
    }

    public function batch($ids = null)
    {
        $id_arr = explode(',', $ids);
        $all_ids = [];
        foreach ($id_arr as $key => $value) {
            $row = $this->model->get($value);
            if ($row) {
                $all_ids[] = $value;
            }
        }

        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $ids = $this->request->get('ids');
            if (empty($ids)) {
                return json([]);
            }

            //查询已复制过当前商品的店铺
            $shop_ids[] = 1;

            $conditions = [];
            $conditions['id'] = ['not in',$shop_ids];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->shop_model
                ->where($where)
                ->where($conditions)
                ->order($sort, $order)
                ->count();

            $list = $this->shop_model
                ->where($where)
                ->where($conditions)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $ids = implode('-', $all_ids);
        $this->assignConfig("goods_id", $ids);
        return $this->view->fetch();
    }

    public function savegoodsshop()
    {
        // 'ids'=>[12,2,1],'goods_id'=>27
        if ($this->request->isAjax()) {
            $params = $this->request->post();
            if (!isset($params['ids']) || empty($params['ids']) || !isset($params['goods_id']) || empty($params['goods_id'])) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $shop_ids = $params['ids'];
            $goods_id = $params['goods_id'];
            $goods_ids = explode('-', $goods_id);
            if (count($shop_ids) == 0 || count($goods_ids) == 0) {
                $this->error('没有可操作的数据');
            }

            foreach ($goods_ids as $key => $value) {
                //查询商品信息
                $goods_info = $this->model->get($value)->toArray();
                if (empty($goods_info)) {
                    continue;
                }

                $goods_data = $goods_info;
                unset($goods_data['id']);
                unset($goods_data['flag_text']);
                unset($goods_data['stock_text']);
                unset($goods_data['specs_text']);
                unset($goods_data['distribution_text']);
                unset($goods_data['activity_text']);
                unset($goods_data['status_text']);
                unset($goods_data['grounding_text']);

                //查询商品sku
                $goods_skus = collection($this->goods_sku_model->where(['goods_id'=>$value])->select())->toArray();

                //查询商品spu
                $goods_spus = collection($this->goods_spu_model->where(['goods_id'=>$value])->select())->toArray();
                write_log_record('商品铺设goods_id:'.$value,'info');
                
                foreach ($shop_ids as $k_shop => $v_shop) {
                    $exist_goods_ids = $this->goods_shop_model->where('goods_id',$value)->column('new_goods_id');
                    if (count($exist_goods_ids) > 0) {
                        $this->model->where(['id'=>['in',$exist_goods_ids],'shop_id'=>$v_shop])->update(['status'=>'hidden','deletetime'=>time()]);
                        $this->goods_shop_model->where(['new_goods_id'=>['in',$exist_goods_ids],'shop_id'=>$v_shop])->delete();
                    }
                    Db::startTrans();
                    try {
                        write_log_record('商品铺设shop_id:'.$v_shop,'info');
                        if ($goods_info['shop_id'] == $v_shop) {
                            throw new Exception("商品铺设失败(goods_id/shop_id:".$value."/".$v_shop.")，失败原因：当前商品所在店铺与目标店铺一致，不能重复铺设");
                        }

                        // if (in_array($v_shop, $exist_shop_ids)) {
                        //     throw new Exception("商品铺设失败(goods_id/shop_id:".$value."/".$v_shop.")，失败原因：当前商品已经铺设过了，不能重复铺设");
                        // }

                        //处理新的商品
                        $goods_data['shop_id'] = $v_shop;

                        // print_r($goods_data);die;
                        $new_goods = $this->model->insert($goods_data);


                        if (empty($new_goods)) {
                            throw new Exception("商品铺设失败(goods_id/shop_id:".$value."/".$v_shop.")，失败原因：商品数据插入数据库失败");
                        }

                        $new_goods_id = $this->model->getLastInsID();
                        if (empty($new_goods)) {
                            throw new Exception("商品铺设失败(goods_id/shop_id:".$value."/".$v_shop.")，失败原因：商品数据插入数据库失败");
                        }

                        //处理商品的sku
                        if(count($goods_skus)>0){
                            foreach ($goods_skus as $k_sku => &$v_sku) {
                                unset($v_sku['id']);
                                unset($v_sku['status_text']);
                                $v_sku['goods_id'] = $new_goods_id;
                            }

                            $sku_res = $this->goods_sku_model->insertAll($goods_skus);
                            if (empty($sku_res)) {
                                throw new Exception("商品铺设失败(goods_id/shop_id:".$value."/".$v_shop.")，失败原因：商品sku数据插入数据库失败");
                            }
                        }

                        //处理商品的spu
                        if(count($goods_spus)>0){
                            foreach ($goods_spus as $k_spu => &$v_spu) {
                                unset($v_spu['id']);
                                unset($v_spu['status_text']);
                                $v_spu['goods_id'] = $new_goods_id;
                            }
                            $spu_res = $this->goods_spu_model->insertAll($goods_spus);
                            if (empty($spu_res)) {
                                throw new Exception("商品铺设失败(goods_id/shop_id:".$value."/".$v_shop.")，失败原因：商品spu数据插入数据库失败");
                            }
                        }

                        //保存商品铺设记录
                        $insert_data = [];
                        $insert_data['shop_id'] = $v_shop;
                        $insert_data['goods_id'] = $value;
                        $insert_data['new_goods_id'] = $new_goods_id;
                        $insert_data['createtime'] = time();
                        $insert_res = $this->goods_shop_model->insert($insert_data);
                        if (empty($insert_res)) {
                            throw new Exception("商品铺设失败(goods_id/shop_id:".$value."/".$v_shop.")，失败原因：商品铺设记录数据插入数据库失败"); 
                        }
                        Db::commit();
                    } catch (ValidateException $e) {
                        Db::rollback();
                        write_log_record($e->getMessage(),'error');
                        continue;
                    } catch (PDOException $e) {
                        Db::rollback();
                        write_log_record($e->getMessage(),'error');
                        continue;
                    } catch (Exception $e) {
                        Db::rollback();
                        write_log_record($e->getMessage(),'error');
                        continue;
                    }
                }
            }
            $this->success('操作成功');
        }
        $this->error(__('You have no permission', ''));
    }

    public function batchdelistingshop()
    {
        // 'ids'=>[12,2,1],'goods_id'=>27
        if ($this->request->isAjax()) {
            $params = $this->request->post();

            if (!isset($params['ids']) || empty($params['ids']) || !isset($params['goods_id']) || empty($params['goods_id'])) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $shop_ids = $params['ids'];
            $goods_id = $params['goods_id'];
            $goods_ids = explode('-', $goods_id);
            if (count($shop_ids) == 0 || count($goods_ids) == 0) {
                $this->error('没有可操作的数据');
            }

            $new_goods_id_arr = [];
            foreach ($goods_ids as $key => $value) {
                //查询商品信息
                $where = [];
                $where['goods_id'] = $value;
                $where['shop_id'] = ['in',$shop_ids];


                $new_goods_id = $this->goods_shop_model->where($where)->column('new_goods_id');
                if (empty($new_goods_id)) {
                    continue;
                }

                $new_goods_id_arr = array_unique(array_merge($new_goods_id, $new_goods_id_arr));
            }

            if (count($new_goods_id_arr)>0) {
                Db::startTrans();
                try {
                    $conditions = [];
                    $conditions['id'] = ['in',$new_goods_id_arr];
                    $result = $this->model->where($conditions)->update(['grounding'=>'0']);
                    if (!$result) {
                        Db::rollback();
                        $this->error('操作失败');
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    write_log_record($e->getMessage(),'error');
                    $this->error('操作失败');
                } catch (PDOException $e) {
                    Db::rollback();
                    write_log_record($e->getMessage(),'error');
                    $this->error('操作失败');
                } catch (Exception $e) {
                    Db::rollback();
                    write_log_record($e->getMessage(),'error');
                    $this->error('操作失败');
                }
            }
            
            $this->success('操作成功');
        }
        $this->error(__('You have no permission', ''));
    }

    public function topgoods()
    {
        //当前管理员店铺id 
        $_admin = Session::get('adminshop');

        //当前店铺id
        $shop_id = Session::get('shop');

        $cur_shop_id = 1;

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $_where = [];
            $_where['gdtype'] = 0;
            $_where['fa_wanlshop_goods.shop_id'] = $cur_shop_id;
            $_where['fa_wanlshop_goods.publishing_platform'] = ['in',['0','2']];

            $total = $this->model
                ->with(['category', 'shopsort', 'shop'])
                ->where($where)
                ->where($_where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['category', 'shopsort', 'shop'])
                ->where($where)
                ->where($_where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->getRelation('category')->visible(['name']);
                $row->getRelation('shopsort')->visible(['name']);
                $row->getRelation('shop')->visible(['shopname']);
            }
            $list = collection($list)->toArray();

            if ($total > 0) {
                foreach ($list as $key => &$value) {
                    $value['already_copy'] = 0;
                    $exist = $this->goods_shop_model->where(['goods_id'=>$value['id'],'shop_id'=>$shop_id])->find();
                    if ($exist && !empty($exist)) {
                        $value['already_copy'] = 1;
                    }
                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function resubmittoshop($ids = null)
    {
        // 'ids'=>[12,2,1],'goods_id'=>27
        if ($this->request->isAjax()) {
            $row = $this->model->get($ids);
            if (!$row) {
                $this->error(__('No Results were found'));
            }

            //当前店铺id
            $shop_id = Session::get('shop');

            $exist = $this->goods_shop_model->where(['goods_id'=>$ids,'shop_id'=>$shop_id])->find();
            if ($exist && !empty($exist)) {
                $this->error(__('当前商品已经添加过了！'));
            }

            $shop_ids = [$shop_id];
            $goods_id = $ids;
            //查询商品信息
            $goods_info = $this->model->get($goods_id)->toArray();
            if (empty($goods_info)) {
                $this->error(__('No Results were found'));
            }

            //查询商品sku
            $goods_skus = collection($this->goods_sku_model->where(['goods_id'=>$goods_id])->select())->toArray();

            //查询商品spu
            $goods_spus = collection($this->goods_spu_model->where(['goods_id'=>$goods_id])->select())->toArray();
            
            Db::startTrans();
            try {
                $goods_data = $goods_info;
                unset($goods_data['id']);
                unset($goods_data['flag_text']);
                unset($goods_data['stock_text']);
                unset($goods_data['specs_text']);
                unset($goods_data['distribution_text']);
                unset($goods_data['activity_text']);
                unset($goods_data['status_text']);
                unset($goods_data['grounding_text']);

                if (count($shop_ids) > 0) {
                    foreach ($shop_ids as $k_shop => $v_shop) {
                        if ($goods_info['shop_id'] == $v_shop) {
                            continue;
                        }
                        //处理新的商品
                        $goods_data['shop_id'] = $v_shop;

                        // print_r($goods_data);die;
                        $new_goods = $this->model->insert($goods_data);


                        if (empty($new_goods)) {
                            Db::rollback();
                            $this->error('操作失败！请稍后重试');
                        }

                        $new_goods_id = $this->model->getLastInsID();

                        //处理商品的sku
                        if(count($goods_skus)>0){
                            foreach ($goods_skus as $k_sku => &$v_sku) {
                                unset($v_sku['id']);
                                unset($v_sku['status_text']);
                                $v_sku['goods_id'] = $new_goods_id;
                            }

                            $sku_res = $this->goods_sku_model->insertAll($goods_skus);
                            if (empty($sku_res)) {
                                Db::rollback();
                                $this->error('操作失败！请稍后重试');
                            }
                        }

                        //处理商品的spu
                        if(count($goods_spus)>0){
                            foreach ($goods_spus as $k_spu => &$v_spu) {
                                unset($v_spu['id']);
                                unset($v_spu['status_text']);
                                $v_spu['goods_id'] = $new_goods_id;
                            }
                            $spu_res = $this->goods_spu_model->insertAll($goods_spus);
                            if (empty($spu_res)) {
                                Db::rollback();
                                $this->error('操作失败！请稍后重试');
                            }
                        }

                        //保存商品铺设记录
                        $insert_data = [];
                        $insert_data['shop_id'] = $v_shop;
                        $insert_data['goods_id'] = $goods_id;
                        $insert_data['new_goods_id'] = $new_goods_id;
                        $insert_data['createtime'] = time();
                        $insert_res = $this->goods_shop_model->insert($insert_data);
                        if (empty($insert_res)) {
                            Db::rollback();
                            $this->error('操作失败！请稍后重试');
                        }
                    }
                }

                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('操作成功');
        }
        $this->error(__('You have no permission', ''));
    }

    /**
     * 详情
     */
    public function detail($ids = null)
    {
        //设置过滤方法
        $this->request->filter(['']);
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // 查询SKU
        $skuItem = model('app\index\model\wanlshop\GoodsSku')
            ->where(['goods_id' => $ids, 'state' => 0])
            ->field('id,thumbnail,difference,price,market_price,stock,weigh,sn,sales,state,cost_price,channel_price,code as skucode,warn_stock')
            ->select();
        $spuData = model('app\index\model\wanlshop\GoodsSpu')->all(['goods_id' => $ids]);
        $suk = [];
        foreach ($skuItem as $vo) {
            $suk[] = explode(",", $vo['difference']);
        }
        $spu = [];
        foreach ($spuData as $vo) {
            $spu[] = $vo['name'];
        }
        $spuItem = [];
        foreach ($spuData as $vo) {
            $spuItem[] = explode(",", $vo['item']);
        }
        $skulist = [];
        foreach ($skuItem as $vo) {
            $skulist[$vo['difference']] = $vo;
        }
        $row->grounding = (string)  $row->grounding;
        $this->assignconfig('spu', $spu);
        $this->assignconfig('spuItem', $spuItem);
        $this->assignconfig('sku', $suk);
        $this->assignconfig('skuItem', $skulist);
        $this->assignconfig('categoryId', $row['category_id']);
        $this->assignconfig('attribute', json_decode($row['category_attribute']));

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 批量操作
     */
    public function multi($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->allowField(true)->isUpdate(true)->save($values);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    /**
     * 复制
     */
    public function reuse($ids = null)
    {
        //设置过滤方法
        $this->request->filter(['']);
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        // 查询SKU
        $skuItem = model('app\index\model\wanlshop\GoodsSku')
            ->where(['goods_id' => $ids, 'state' => 0])
            ->field('id,thumbnail,difference,price,market_price,stock,weigh,sn,sales,state,cost_price,channel_price,code as skucode,warn_stock')
            ->select();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $result = false;
                Db::startTrans();
                try {
                    $skudata = isset($params['sku']) && !empty($params['sku'])?$params['sku'] : [];
                    $spudata = isset($params['spu']) && !empty($params['spu'])?$params['spu'] : '';
                    $spuItem = isset($params['spuItem']) && !empty($params['spuItem'])?$params['spuItem'] : [];
                    // 写入表单
                    $data = $params;
                    if (isset($data['attribute'])) {
                        $data['category_attribute'] = json_encode($data['attribute'], JSON_UNESCAPED_UNICODE);
                    }

                    $data['shop_id'] =$row->shop_id;
                    $data['createtime'] = time();
                    $data['updatetime'] = time();

                    unset($data['sku']);
                    unset($data['spu']);
                    unset($data['spuItem']);
                    unset($data['cost_price']);
                    unset($data['channel_price']);
                    unset($data['stocks']);
                    unset($data['warn_stock']);
                    unset($data['skucode']);
                    unset($data['flag']);
                    $result = true;
                    $goods_id = $this->model->insertGetId($data);
                    if (!$goods_id || empty($goods_id)) {
                        $result = false;
                    }

                    // 写入SPU
                    $spu = [];
                    if (!empty($spudata)) {
                        foreach (explode(",", $spudata) as $key => $value) {
                            $spu[] = [
                                'goods_id' => $goods_id,
                                'name'     => $value,
                                'item'     => $spuItem[$key]
                            ];
                        }
                    }else{
                        $spu[] = [
                            'goods_id' => $goods_id,
                            'name'     => $this->unitList[$data['unit']],
                            'item'     => $this->unitList[$data['unit']],
                        ];
                    }

                    if (!$this->goods_spu_model->allowField(true)->saveAll($spu)) {
                        $result == false;
                    }

                    // 写入SKU
                    $sku = [];
                    $goods_min_price = $params['price'];

                    if (count($skudata) > 0) {
                        foreach ($params['sku']['sku_name'] as $_key => $_value) {
                            $sku[] = [
                                'goods_id'      => $goods_id,
                                'difference'    => $_value,
                                'code'          => $params['sku']['skucode'][$_key],
                                'cost_price'    => $params['sku']['cost_price'][$_key], // 1.0.8升级
                                'channel_price' => $params['sku']['channel_price'][$_key], // 1.0.8升级
                                'price'         => $params['sku']['price'][$_key],
                                'stock'         => $params['sku']['stocks'][$_key],
                                'warn_stock'   => $params['sku']['warn_stock'][$_key],
                                'sn'            => $params['sku']['skucode'][$_key]
                            ];
                        }
                        $goods_min_price = min($params['sku']['price']);
                    }else{
                        $sku[] = [
                            'goods_id'      => $goods_id,
                            'difference'    => $this->unitList[$data['unit']],
                            'code'          => $params['code'],
                            'cost_price'    => $params['price'], // 1.0.8升级
                            'channel_price' => $params['price'], // 1.0.8升级
                            'price'         => $params['price'],
                            'stock'         => 99,
                            'warn_stock'   => 1,
                            'sn'            => $params['code']
                        ];
                    }
                    if (!$this->goods_sku_model->allowField(true)->saveAll($sku)) {
                        $result == false;
                    }

                    if ($goods_min_price != $params['price'] ) {
                         if (!$this->model->where('id',$goods_id)->update(['price'=>$goods_min_price])) {
                            $result == false;
                        }
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $spuData = model('app\index\model\wanlshop\GoodsSpu')->all(['goods_id' => $ids]);
        $suk = [];
        foreach ($skuItem as $vo) {
            $suk[] = explode(",", $vo['difference']);
        }
        $spu = [];
        foreach ($spuData as $vo) {
            $spu[] = $vo['name'];
        }
        $spuItem = [];
        foreach ($spuData as $vo) {
            $spuItem[] = explode(",", $vo['item']);
        }
        $skulist = [];
        foreach ($skuItem as $vo) {
            $skulist[$vo['difference']] = $vo;
        }
        $row->grounding = (string)  $row->grounding;
        $this->assignconfig('spu', $spu);
        $this->assignconfig('spuItem', $spuItem);
        $this->assignconfig('sku', $suk);
        $this->assignconfig('skuItem', $skulist);
        $this->assignconfig('categoryId', $row['category_id']);
        $this->assignconfig('attribute', json_decode($row['category_attribute']));

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        $skucount = 0;
        $spucount = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }

            if ($count) {
                $skucount += $this->goods_sku_model->where(['goods_id'=>['in',$ids]])->delete();
                $spucount += $this->goods_spu_model->where(['goods_id'=>['in',$ids]])->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count && $skucount && $spucount) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    /**
    * 获取商品关联的店铺分页列表
    */
    public function onsaleshops()
    {
        // 获取主表ID和分页参数
        $id = $this->request->get('id/d', 0);
        $page = $this->request->get('page/d', 1);
        $limit = $this->request->get('limit/d', 10);
        
        if (!$id) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }
        
        $ids = $this->goods_shop_model->where(['goods_id'=>$id])->column('new_goods_id');
        $shop_on_sale = [];

        $list = [];
        if (count($ids)>0) {
            $shop_on_sale = $this->model->where(['id'=>['in',$ids],'grounding'=>'1'])->column('shop_id');
        }

        if (count($shop_on_sale) == 0) {
            return json(['code' => 1, 'msg' => '没有门店在售当前商品']);
        }

        $conditions = [];
        $conditions['id'] = ['in',$shop_on_sale];
        $conditions['status'] = 'normal';

        // 获取总数
        $total = $this->shop_model->where($conditions)->count();
        
        // 获取分页数据
        $list = $this->shop_model->where($conditions)->page($page, $limit)->select();
        
        // 返回分页数据
        return json([
            'code' => 0,
            'msg' => '获取成功',
            'total' => $total,
            'per_page' => $limit,
            'current_page' => $page,
            'last_page' => ceil($total / $limit),
            'data' => $list
        ]);
    }

    public function shoplist()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $conditions = [];
            $conditions['id'] = ['<>',1];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->shop_model
                ->where($where)
                ->where($conditions)
                ->order($sort, $order)
                ->count();

            $list = $this->shop_model
                ->where($where)
                ->where($conditions)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function batchUpdatePrice()
    {
        // 检查请求类型
        if (!$this->request->isPost()) {
            $this->error('非法请求');
        }
        
        // 获取参数
        $params = $this->request->post();
        $goodsIds = $params['goods_ids'] ?? [];
        $shopIds = $params['shop_ids'] ?? [];
        $price = $params['price'] ?? 0;
        $title = trim($params['title']) ?? '';
        
        // 数据验证
        if (empty($goodsIds) || !is_array($goodsIds) || count($goodsIds) == 0) {
            $this->error('请选择商品');
        }
        
        if (empty($shopIds) || !is_array($shopIds) || count($shopIds) == 0) {
            $this->error('请选择店铺');
        }
        
        if ($price <= 0) {
            $this->error('价格必须大于0');
        }
        
        try {
            // 开始事务
            Db::startTrans();
            
            foreach ($goodsIds as $_key => $_value) {
                $conditions = [];
                $conditions['goods_id'] = $_value;
                $conditions['shop_id'] = ['in',$shopIds];
                $newGoodsIds = $this->goods_shop_model->where($conditions)->column('new_goods_id');
                if(count($newGoodsIds) == 0){
                    continue;
                }
                $newGoodsIds[] = $_value;

                // 更新商品价格
                $conditions = [];
                $conditions['id'] = ['in',$newGoodsIds];
                $updateData = [];
                $updateData['price'] = $price;
                $updateData['updatetime'] = time();
                if (!empty($title)) $updateData['title'] = $title;
                $result = $this->model->where($conditions)->update($updateData);

                if(!$result || empty($result)){
                    Db::rollback();
                    exception('价格更新失败！');
                }

                // 更新商品属性价格
                $conditions = [];
                $conditions['goods_id'] = ['in',$newGoodsIds];
                $updateData = [];
                $updateData['price'] = $price;
                $updateData['updatetime'] = time();
                $result = $this->goods_sku_model->where($conditions)->update($updateData);
                if(!$result || empty($result)){
                    Db::rollback();
                    exception('价格更新失败！');
                }
                
            }
            Db::commit();
            $this->success('更新成功！','',[]);
        } catch (Exception $e) {
            Db::rollback();
            $this->error('操作失败，请稍后重试！');
        }
    }
}
